<template>
  <div 
    :style="{ 
      position: 'absolute',
      zIndex: component.zIndex,
      pointerEvents: isPreview ? 'auto' : 'none'
    }"
    @click.stop="handleSelect"
  >
    <!-- 1. 组件名替换为 Vue3DraggableResizable -->
    <vue3-draggable-resizable
      :x="component.x"
      :y="component.y"
      :width="component.width"
      :height="component.height"
      :snap="snapToGrid"
      :snap-tolerance="5"
     
      :grid="[gridSize, gridSize]"
     
      :active="isSelected && !isPreview"
      :resizable="!isPreview"
      :draggable="!isPreview"
       @drag-start="onDragStop"
      
      @drag-stop="onDragStop"
      @resize-stop="onResizeStop"
      class="component-wrapper"
      :style="{ 
        pointerEvents: 'auto',
        border: isSelected && !isPreview ? '2px solid #409eff' : 'none',
        borderRadius: '2px'
      }"
    >
      <!-- 组件内容（与原逻辑一致） -->
      <component 
        :is="getComponentByType(component.type)" 
        :component="component" 
        :is-preview="isPreview"
      />
      
      <!-- 选中状态下的操作工具栏（与原逻辑一致） -->
      <div v-if="isSelected && !isPreview" class="absolute -bottom-8 left-0 right-0 flex justify-center gap-1 bg-white px-2 py-1 rounded shadow text-xs z-10">
        <el-button 
          size="mini" 
          icon="el-icon-top" 
          @click.stop="handleZIndexUp" 
          :disabled="index === 0"
        />
        <el-button 
          size="mini" 
          icon="el-icon-bottom" 
          @click.stop="handleZIndexDown" 
          :disabled="index === componentsLength - 1"
        />
        <el-button 
          size="mini" 
          icon="el-icon-copy-document" 
          @click.stop="handleDuplicate"
        />
        <el-button 
          size="mini" 
          icon="el-icon-delete" 
          @click.stop="handleRemove"
          type="danger"
        />
      </div>
    </vue3-draggable-resizable>
  </div>
</template>

<script>
import { defineProps } from 'vue'; // ref未使用，可移除

import Vue3DraggableResizable from '@v3e/vue3-draggable-resizable'
//需引入默认样式
import '@v3e/vue3-draggable-resizable/dist/Vue3DraggableResizable.css'


import { ElMessage } from 'element-plus';
import { v4 as uuidv4 } from 'uuid';

// 导入所有子组件（与原逻辑一致）
import TextComponent from '../basic/TextComponent.vue';
import ImageComponent from '../basic/ImageComponent.vue';
import RectangleComponent from '../basic/RectangleComponent.vue';
import CircleComponent from '../basic/CircleComponent.vue';
import LineComponent from '../basic/LineComponent.vue';
import ButtonComponent from '../basic/ButtonComponent.vue';
import LineChart from '../charts/LineChart.vue';
import PieChart from '../charts/PieChart.vue';
import ContainerComponent from './ContainerComponent.vue';

// 组件映射关系（与原逻辑一致）
const componentMap = {
  text: TextComponent,
  image: ImageComponent,
  rectangle: RectangleComponent,
  circle: CircleComponent,
  line: LineComponent,
  button: ButtonComponent,
  'line-chart': LineChart,
  'pie-chart': PieChart,
  container: ContainerComponent,
};

export default {
  // 5. 注册Vue3版本的组件
  components: {
    Vue3DraggableResizable
  },
  props: {
    component: {
      type: Object,
      required: true,
      description: '组件数据'
    },
    index: {
      type: Number,
      required: true,
      description: '组件索引'
    },
    snapToGrid: {
      type: Boolean,
      default: true,
      description: '是否吸附到网格'
    },
    gridSize: {
      type: Number,
      default: 20,
      description: '网格大小'
    },
    isSelected: {
      type: Boolean,
      default: false,
      description: '是否选中'
    },
    isPreview: {
      type: Boolean,
      default: false,
      description: '是否预览模式'
    },
    componentsLength: {
      type: Number,
      required: true,
      description: '组件总数'
    }
  },
  emits: ['select', 'update', 'remove', 'z-index-up', 'z-index-down'],
  setup(props, { emit }) {
    // 根据类型获取组件（与原逻辑一致）
    const getComponentByType = (type) => {
      return componentMap[type] || TextComponent;
    };
    
    // 处理组件选中（与原逻辑一致）
    const handleSelect = () => {
      if (!props.isPreview) {
        emit('select', props.component.id);
      }
    };
    
    // 6. 拖拽结束事件：Vue3版本返回{ x, y }对象（原版本返回x,y两个参数）
    const onDragStop = ({ x, y }) => {
      emit('update', props.component.id, { x, y });
    };
    
    // 7. 调整大小结束事件：Vue3版本返回{ x, y, width, height }对象（原版本返回4个参数）
    const onResizeStop = ({ x, y, width, height }) => {
      emit('update', props.component.id, { x, y, width, height });
    };
    
    // 移除组件（与原逻辑一致）
    const handleRemove = () => {
      emit('remove', props.component.id);
    };
    
    // 层级上移（与原逻辑一致）
    const handleZIndexUp = () => {
      emit('z-index-up');
    };
    
    // 层级下移（与原逻辑一致）
    const handleZIndexDown = () => {
      emit('z-index-down');
    };
    
    // 复制组件（与原逻辑一致，建议补充emit逻辑）
    const handleDuplicate = () => {
      const newComponent = {
        ...JSON.parse(JSON.stringify(props.component)),
        id: uuidv4(),
        x: props.component.x + 20,
        y: props.component.y + 20,
        zIndex: props.component.zIndex + 1
      };
      
      ElMessage.success('组件已复制');
      // 补充：原逻辑未 emit 复制事件，父组件无法接收新组件，建议添加：
      // emit('duplicate', newComponent);
    };
    
    return {
      getComponentByType,
      handleSelect,
      onDragStop,
      onResizeStop,
      handleRemove,
      handleZIndexUp,
      handleZIndexDown,
      handleDuplicate
    };
  }
};
</script>

<style scoped>
.component-wrapper {
  overflow: hidden;
}
</style>